package com.wash.ctrl.user;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wash.model.User;
import com.wash.service.ShoppingCartService;
import com.wash.service.UserService;


@Lazy(true)
@Controller
@RequestMapping
public class UserCtrl {

	private static final String GOODS_PREFEX="gid-";
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private ShoppingCartService shoppingCartService;
	
	/**
	 * 登录
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping
	@ResponseBody
	public String login(HttpServletRequest request,HttpServletResponse response){
		String phone=request.getParameter("phone");
		String password=request.getParameter("password");
		User user=userService.getUser(phone, password);
		if(user==null){
			return "1-用户名或密码不正确";
		}
		HttpSession session = request.getSession(true);
		session.setAttribute("user", user);
		//把Cookie里的商品加入购物车
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie c : cookies) {
				String cookieName = c.getName();
				if (cookieName.startsWith(GOODS_PREFEX)) {
					int goodsId = Integer.parseInt(cookieName.split("-")[1]);
					int quantity = Integer.parseInt(c.getValue());
					shoppingCartService.changeCartItem(user.getId(), goodsId,quantity, 0);
					c.setMaxAge(0);
					response.addCookie(c);
				}
			}
		}
		return "0";
	}
	
	/**
	 * 注册
	 * @param request
	 * @return
	 */
	@RequestMapping
	@ResponseBody
	public String register(HttpServletRequest request){
		String phone=request.getParameter("phone");
		String password=request.getParameter("password");
		boolean flag=userService.hasRegister(phone);
		if(flag){
			return "1-该手机号已注册";
		}
		User user=new User();
		user.setPhone(phone);
		user.setPassword(password);
		userService.add(user);
		HttpSession session = request.getSession(true);
		session.setAttribute("user", user);
		return "0";
	}
	
	
	
}
